import { GetUserInfo, SetUserInfo, GetIndustryList, SetTaskScore } from "@/api";

const genderMap = {
    男: 1,
    女: 0,
};

export const useContent = () => {
    const form = ref({});
    const industryList = ref([]);
    const updatePhoneDialogRef = ref(null);

    const onGetUserInfo = async () => {
        const res = await GetUserInfo();

        if (res.code == 200) {
            form.value = {
                ...res.data,
                city: (res.data.city || "").split("/"),
                gender: genderMap[res.data.gender] || 0,
                personal_ignature: res.data.personal_ignature || "",
            };
        }
    };

    const onGetList = async () => {
        const res = await GetIndustryList();
        if (res.code == 200) {
            industryList.value = res.data;
        }
    };

    const onSubmit = async () => {
        if (String(form.value.nickname).trim() == "") {
            Message().warning("请完善用户名");
            return false;
        } else if (String(form.value.industry_id).trim() == "") {
            Message().warning("请完善所属行业");
            return false;
        } else if (String(form.value.city).trim() == "") {
            Message().warning("请完善所在地");
            return false;
        } else if (String(form.value.gender).trim() == "") {
            Message().warning("请完善性别");
            return false;
        } else if (String(form.value.birthday).trim() == "") {
            Message().warning("请完善出生日期");
            return false;
        }

        const res = await SetUserInfo({
            gender: form.value.gender,
            nickname: form.value.nickname,
            industry_id: form.value.industry_id
                ? form.value.industry_id[form.value.industry_id.length - 1]
                : "",
            city: form.value.city.join("/"),
            birthday: form.value.birthday,
            hobby: form.value.hobby,
            personal_ignature: form.value.personal_ignature,
        });

        if (res.code == 200) {
            Message().success("保存成功！");
            // 判断信息字段获取积分
            if (form.value.nickname) {
                await SetTaskScore({
                    code: 1010,
                });
            }
        }
    };

    const onUpdatePassword = () => {
        navigateTo("/updatePwd");
    };

    const onUpdatePhone = () => {
        updatePhoneDialogRef.value.show();
    };

    const birthdayDisabled = (date) => {
        return date > new Date();
    };

    return {
        form,
        industryList,
        updatePhoneDialogRef,
        birthdayDisabled,
        onGetList,
        onGetUserInfo,
        onSubmit,
        onUpdatePassword,
        onUpdatePhone,
    };
};
